# routers/specifications.py
from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session
from typing import List
from db import ProductSpecification
from pydantic import BaseModel

router = APIRouter(prefix="/specifications", tags=["specifications"])

# Pydantic 模型定义
class ProductSpecificationCreate(BaseModel):
    product_id: int
    parameter_name: str
    parameter_value: str

class ProductSpecificationResponse(ProductSpecificationCreate):
    id: int
    
    class Config:
        orm_mode = True

# 依赖项
def get_db():
    from db import SessionLocal
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()

# ProductSpecification 相关 API
@router.post("/", response_model=ProductSpecificationResponse)
def create_specification(spec: ProductSpecificationCreate, db: Session = Depends(get_db)):
    db_spec = ProductSpecification(**spec.dict())
    db.add(db_spec)
    db.commit()
    db.refresh(db_spec)
    return db_spec

@router.get("/", response_model=List[ProductSpecificationResponse])
def read_specifications(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)):
    specs = db.query(ProductSpecification).offset(skip).limit(limit).all()
    return specs

@router.get("/{spec_id}", response_model=ProductSpecificationResponse)
def read_specification(spec_id: int, db: Session = Depends(get_db)):
    db_spec = db.query(ProductSpecification).filter(ProductSpecification.id == spec_id).first()
    if db_spec is None:
        raise HTTPException(status_code=404, detail="Specification not found")
    return db_spec

@router.put("/{spec_id}", response_model=ProductSpecificationResponse)
def update_specification(spec_id: int, spec: ProductSpecificationCreate, db: Session = Depends(get_db)):
    db_spec = db.query(ProductSpecification).filter(ProductSpecification.id == spec_id).first()
    if db_spec is None:
        raise HTTPException(status_code=404, detail="Specification not found")
    
    for key, value in spec.dict().items():
        setattr(db_spec, key, value)
        
    db.commit()
    db.refresh(db_spec)
    return db_spec

@router.delete("/{spec_id}", response_model=ProductSpecificationResponse)
def delete_specification(spec_id: int, db: Session = Depends(get_db)):
    db_spec = db.query(ProductSpecification).filter(ProductSpecification.id == spec_id).first()
    if db_spec is None:
        raise HTTPException(status_code=404, detail="Specification not found")
    
    db.delete(db_spec)
    db.commit()
    return db_spec